<?php

namespace App\Trip\Plane\Interfaces\Result\Wrappers;

use App\Trip\Plane\Interfaces\Result\Abstracts\AbstractFlightQueryResult;
use App\Trip\Plane\Requests\TicketQueryRequest;
use Illuminate\Support\Collection;

class PlaneQueryResultFilterWrapper extends AbstractFlightQueryResult
{
    private Collection         $lists;
    private TicketQueryRequest $request;

    public function __construct(AbstractFlightQueryResult $res, TicketQueryRequest $request)
    {
        $this->lists   = $res->getLists();
        $this->request = $request;
    }

    public function getLists(): Collection
    {
        $arrive_airports = $this->request->getArriveAirports();
        $depart_airports = $this->request->getDepartAirports();
        $plane_types     = $this->request->getPlaneTypes();
        $cabins          = $this->request->getCabins();
        $depart_time     = $this->request->getDepartTime();
        if ($arrive_airports) {
            $this->lists = collect($this->lists)->whereIn('to_code', array_column($arrive_airports, 'airport_code'));
        }
        if ($depart_airports) {
            $this->lists = collect($this->lists)->whereIn('from_code', array_column($depart_airports, 'airport_code'));
        }
        if ($plane_types) {
            $this->lists = collect($this->lists)->whereIn('plane_type', $plane_types);
        }
        if ($cabins) {
            $this->lists = collect($this->lists)->whereIn('cabin', array_column($cabins, 'cabin'));
        }

        $depart_times = config('trip.airplane.depart_times');
        if ($depart_time && in_array($depart_time, $depart_times)) {
            $this->lists = collect($this->lists)->filter(function ($flight) use ($depart_time) {
                $part = explode('-', $depart_time);
                return $flight->depart_time >= $part[0] && $flight->depart_time <= $part[1];
            });
        }
        return $this->lists;
    }


    public function getCount(): int
    {
        return $this->lists->count();
    }
}